package com.minimalist.common.config.sentinel;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Sentinel资源定义类
 *
 * @author minimalist
 */
@Component
public class SentinelResourceDefine {
    private static final Logger log = LoggerFactory.getLogger(SentinelResourceDefine.class);


    /**
     * 初始化Sentinel规则
     */
    @PostConstruct
    public void initSentinelRules() {
        log.info("初始化Sentinel规则");
        initFlowRules();
        initDegradeRules();
    }

    /**
     * 初始化流控规则
     */
    private void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();

        // 为每个服务创建流控规则
        String[] services = { "minimalist-tc", "minimalist-lindi" };
        for (String service : services) {
            FlowRule rule = new FlowRule();
            rule.setResource(service);
            rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 基于QPS限流
            rule.setCount(100); // 每秒允许100个请求
            rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP); // 预热模式
            rule.setWarmUpPeriodSec(10); // 预热时间10秒
            rules.add(rule);
        }

        FlowRuleManager.loadRules(rules);
        log.info("初始化流控规则完成，共{}条规则", rules.size());
    }

    /**
     * 初始化熔断规则
     */
    private void initDegradeRules() {
        List<DegradeRule> rules = new ArrayList<>();

        // 为每个服务创建熔断规则
        String[] services = { "minimalist-tc", "minimalist-lindi" };
        for (String service : services) {
            DegradeRule rule = new DegradeRule();
            rule.setResource(service);
            rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO); // 基于异常比例熔断
            rule.setCount(0.5); // 异常比例阈值，0.5表示50%
            rule.setTimeWindow(10); // 熔断时间窗口，单位秒
            rule.setMinRequestAmount(10); // 熔断触发的最小请求数
            rule.setStatIntervalMs(1000); // 统计时间窗口，单位毫秒
            rules.add(rule);
        }

        DegradeRuleManager.loadRules(rules);
        log.info("初始化熔断规则完成，共{}条规则", rules.size());
    }
}
